package com.rc.activity;

import java.util.ArrayList;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_ItemDao;
import com.rc.activity.dao.tbl_Merchant;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_ReceiptDao;
import com.rc.activity.dao.tbl_Report;
import com.rc.activity.dao.tbl_ReportDao;
import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.dao.tbl_TripDao;
import com.rc.activity.dao.tbl_TripItems;
import com.rc.activity.dao.tbl_TripItemsDao;
import com.rc.activity.provider.ContentProviderApp;
import com.rc.activity.provider.Contract;
import com.rc.db.DatabaseSupport;
import com.rc.net.NetSupport;
import com.rc.object.BaseObject;
import com.rc.object.ItemsObj;
import com.rc.object.MerchantObj;
import com.rc.object.ReceiptObj;
import com.rc.object.ReportObj;
import com.rc.object.TripItemsObj;
import com.rc.object.TripObj;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class LoadData extends BaseActivity {

	private ArrayList<tbl_TripItems> arrTripItems;
	private ArrayList<tbl_Trip> arrTrips;
	private ArrayList<tbl_Report> arrReports;
	private ArrayList<tbl_Receipt> arrReceipts;
	private ArrayList<tbl_Item> arrItems;
	private ArrayList<tbl_Merchant> arrMerchants;

	private int isLoad = 0;

	// register animation
	private TextView leftRightTvOne;
	private TextView leftRightTvTwo;
	private TextView leftRightTvThree;
	private int screenWidth;
	private AnimatorSet animatorSet;
	private AnimatorSet animatorSet1;

	public static void callIntemt(Activity ct, int isLoad) {
		Intent it = new Intent(ct, LoadData.class);
		it.putExtra("IS_LOAD", isLoad);
		ct.startActivity(it);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.load_data);
		leftToRightToLeftMove();
		if (getIntent().hasExtra("IS_LOAD")) {
			isLoad = getIntent().getIntExtra("IS_LOAD", 0);
		}
		if (Util.isNetworkActivated(LoadData.this)) {
			new insertReports().execute("");
		} else {
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * insert tripitems
	 */
	private class insertTripItems extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {
			return NetSupport.get_TripItems(arrReceipts);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			arrTripItems = new ArrayList<tbl_TripItems>();
			for (BaseObject objBase : result) {
				tbl_TripItems objTripItems = new tbl_TripItems();
				objTripItems = TripItemsObj.getObjTripByBaseObject(objBase);
				if (objTripItems != null) {
					arrTripItems.add(objTripItems);
				}
			}
			new insertSQL().execute("");
		}

	}

	/**
	 * insert tripitems
	 */
	private class insertSQL extends AsyncTask<String, Void, Void> {

		protected Void doInBackground(String... urls) {
			insertSQL();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			finish();
		}

	}

	private void insertSQL() {
		for (tbl_Report objReport : arrReports) {

			if (DatabaseSupport.getReportByID(objReport.getReportID(),
					LoadData.this) == null) {
				objReport.setIsCreate("2");
				LoadData.this.getContentResolver().insert(
						Contract.CONTENT_URI_REPORT,
						objReport.getContentValues());
			}

		}
		for (tbl_Trip objTrip : arrTrips) {
			if (DatabaseSupport.getTripByID(objTrip.getTripID(), LoadData.this) == null) {
				objTrip.setIsCreate("2");
				LoadData.this.getContentResolver().insert(
						Contract.CONTENT_URI_TRIP, objTrip.getContentValues());
			}
		}
		for (tbl_TripItems objTripItems : arrTripItems) {
			if (DatabaseSupport.getTripItemsByID(objTripItems.getTripItemID(),
					LoadData.this) == null) {
				objTripItems.setIsCreate("2");
				LoadData.this.getContentResolver().insert(
						Contract.CONTENT_URI_TRIP_ITEM,
						objTripItems.getContentValues());
			}
		}
		for (tbl_Merchant objMerchant : arrMerchants) {
			if (DatabaseSupport.getMerchantByID(objMerchant.getMerchantID(),
					LoadData.this) == null) {
				objMerchant.setIsCreate("2");
				LoadData.this.getContentResolver().insert(
						Contract.CONTENT_URI_MERCHANT,
						objMerchant.getContentValues());
			}
		}
		for (tbl_Receipt objReceipt : arrReceipts) {
			if (DatabaseSupport.getReceiptByID(objReceipt.getReceiptID(),
					LoadData.this) == null) {
				objReceipt.setIsCreate("2");
				LoadData.this.getContentResolver().insert(
						Contract.CONTENT_URI_RECEIPT,
						objReceipt.getContentValues());
			}
		}
		String sqlReport = "UPDATE " + tbl_ReportDao.TABLENAME + " SET "
				+ tbl_ReportDao.Properties.IsCreate.columnName + " = '' where "
				+ tbl_ReportDao.Properties.IsCreate.columnName + " = '2'";
		String sqlReceipt = "UPDATE " + tbl_ReceiptDao.TABLENAME + " SET "
				+ tbl_ReceiptDao.Properties.IsCreate.columnName
				+ " = '' where "
				+ tbl_ReceiptDao.Properties.IsCreate.columnName + " = '2'";
		String sqlTrip = "UPDATE " + tbl_TripDao.TABLENAME + " SET "
				+ tbl_TripDao.Properties.IsCreate.columnName + " = '' where "
				+ tbl_TripDao.Properties.IsCreate.columnName + " = '2'";
		String sqlItem = "UPDATE " + tbl_ItemDao.TABLENAME + " SET "
				+ tbl_ItemDao.Properties.IsCreate.columnName + " = '' where "
				+ tbl_ItemDao.Properties.IsCreate.columnName + " = '2'";
		String sqlTripItem = "UPDATE " + tbl_TripItemsDao.TABLENAME + " SET "
				+ tbl_TripItemsDao.Properties.IsCreate.columnName
				+ " = '' where "
				+ tbl_TripItemsDao.Properties.IsCreate.columnName + " = '2'";
		ContentProviderApp.db.execSQL(sqlReport);
		ContentProviderApp.db.execSQL(sqlReceipt);
		ContentProviderApp.db.execSQL(sqlTrip);
		ContentProviderApp.db.execSQL(sqlItem);
		ContentProviderApp.db.execSQL(sqlTripItem);

	}

	/**
	 * insert items
	 */
	private class insertItems extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {
			return NetSupport.get_Items(arrReceipts);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			super.onPostExecute(result);
			arrItems = new ArrayList<tbl_Item>();
			for (BaseObject objBase : result) {
				tbl_Item objItem = new tbl_Item();
				objItem = ItemsObj.getObjItemByBaseObject(objBase);
				if (objItem != null) {
					arrItems.add(objItem);
				}
			}
			if (Util.isNetworkActivated(LoadData.this)) {
				new insertTripItems().execute("");
			} else {
				showToast(getString(R.string.no_connection));
			}

		}

	}

	/**
	 * insert merchant
	 */
	private class insertMerchant extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {
			return NetSupport.get_Merchants(arrReceipts);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			super.onPostExecute(result);
			arrMerchants = new ArrayList<tbl_Merchant>();
			for (BaseObject objBase : result) {
				tbl_Merchant objMerchant = new tbl_Merchant();
				objMerchant = MerchantObj.getObjMerchantByBaseObject(objBase);
				if (objMerchant != null) {
					arrMerchants.add(objMerchant);
				}
			}
			if (Util.isNetworkActivated(LoadData.this)) {
				new insertItems().execute("");
			} else {
				showToast(getString(R.string.no_connection));
			}

		}

	}

	/**
	 * insert Trips
	 */
	private class insertTrip extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {
			return NetSupport.get_Trip(arrReports);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			super.onPostExecute(result);
			arrTrips = new ArrayList<tbl_Trip>();
			for (BaseObject objBase : result) {
				tbl_Trip objTrip = new tbl_Trip();
				objTrip = TripObj.getObjTripByBaseObject(objBase);
				if (objTrip != null) {
					arrTrips.add(objTrip);
				}
			}

			if (arrTrips != null) {
				if (arrTrips.size() > 0) {
					if (Util.isNetworkActivated(LoadData.this)) {
						new insertReceips().execute("");
					} else {
						showToast(getString(R.string.no_connection));
					}

				} else {
					finish();
				}
			} else {
				finish();
			}
		}

	}

	/**
	 * insert Trip Free
	 */
	private class insertTripFree extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {

			return NetSupport.get_Trip_free(20, LoadData.this);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			arrTrips = new ArrayList<tbl_Trip>();
			for (BaseObject objBase : result) {
				tbl_Trip objTrip = new tbl_Trip();
				objTrip = TripObj.getObjTripByBaseObject(objBase);
				if (objTrip != null) {
					arrTrips.add(objTrip);
				}
			}

			if (arrTrips != null) {
				if (arrTrips.size() > 0) {
					if (Util.isNetworkActivated(LoadData.this)) {
						new insertReceips().execute("");
					} else {
						showToast(getString(R.string.no_connection));
					}

				} else {
					if (isLoad == 2) {
						mFinish();
					} else {
						new insertReceipsFree().execute("");
					}
				}
			} else {
				mFinish();
			}
		}
	}

	/**
	 * insert Reports
	 */
	private class insertReports extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {
			return NetSupport.get_Report("30", "1", LoadData.this);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			super.onPostExecute(result);
			arrReports = new ArrayList<tbl_Report>();
			for (BaseObject objBase : result) {
				tbl_Report objReport = new tbl_Report();
				objReport = ReportObj.getReportbyBaseObject(objBase);
				if (objReport != null) {
					arrReports.add(objReport);
				}
			}
			if (arrReports != null) {
				if (arrReports.size() > 0) {
					if (Util.isNetworkActivated(LoadData.this)) {
						new insertTrip().execute("");
					} else {
						showToast(getString(R.string.no_connection));
					}

				} else {
					if (isLoad == 1) {
						mFinish();
					} else {
						new insertTripFree().execute("");
					}

				}
			} else {
				mFinish();
			}
		}

	}

	/**
	 * insert Receipts
	 */
	private class insertReceips extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {
			return NetSupport.get_Receipt(arrTrips);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			super.onPostExecute(result);
			arrReceipts = new ArrayList<tbl_Receipt>();
			for (BaseObject objBase : result) {
				tbl_Receipt objReceipt = new tbl_Receipt();
				objReceipt = ReceiptObj.getReceiptbyBaseObject(objBase);
				if (objReceipt != null) {
					arrReceipts.add(objReceipt);
				}
			}
			if (Util.isNetworkActivated(LoadData.this)) {
				new insertMerchant().execute("");
			} else {
				showToast(getString(R.string.no_connection));
			}

		}

	}

	/**
	 * insert Receipt free
	 */
	private class insertReceipsFree extends
			AsyncTask<String, Void, ArrayList<BaseObject>> {

		protected ArrayList<BaseObject> doInBackground(String... urls) {
			arrReceipts = new ArrayList<tbl_Receipt>();
			Cursor cursor = LoadData.this.getContentResolver().query(
					Contract.CONTENT_URI_RECEIPT, null, null, null, null);
			arrReceipts = tbl_Receipt.getObjectbyCursor(cursor);
			return NetSupport.get_ReceiptFree(arrReceipts, 30);
		}

		@Override
		protected void onPostExecute(ArrayList<BaseObject> result) {
			super.onPostExecute(result);
			arrReceipts = new ArrayList<tbl_Receipt>();
			for (BaseObject objBase : result) {
				tbl_Receipt objReceipt = new tbl_Receipt();
				objReceipt = ReceiptObj.getReceiptbyBaseObject(objBase);
				if (objReceipt != null) {
					arrReceipts.add(objReceipt);
				}
			}
			if (arrReceipts != null) {
				if (arrReceipts.size() > 0) {
					if (Util.isNetworkActivated(LoadData.this)) {
						new insertMerchant().execute("");
					} else {
						showToast(getString(R.string.no_connection));
					}
				}
			}

		}

	}

	/**
	 * finish activity when load all data
	 */
	private void mFinish() {
		showToast(getString(R.string.all_of_your_data_are_loaded));
		finish();
	}

	@SuppressLint("NewApi")
	public void leftToRightToLeftMove() {
		leftRightTvOne = (TextView) findViewById(R.id.leftRightTvOne);
		leftRightTvTwo = (TextView) findViewById(R.id.leftRightTvTwo);
		leftRightTvThree = (TextView) findViewById(R.id.leftRightTvThree);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		screenWidth = displaymetrics.widthPixels;

		final ValueAnimator valueTvOne_x = ObjectAnimator.ofFloat(
				leftRightTvOne, "x", leftRightTvOne.getX(), screenWidth * .9f);

		valueTvOne_x.setDuration(1000);
		valueTvOne_x.setRepeatCount(0);
		valueTvOne_x.setRepeatMode(ValueAnimator.REVERSE);
		valueTvOne_x.setInterpolator(new DecelerateInterpolator());

		final ValueAnimator valueTvTwo_x = ObjectAnimator.ofFloat(
				leftRightTvTwo, "x", leftRightTvTwo.getX(), screenWidth * .93f);// -
																				// 35);

		valueTvTwo_x.setDuration(1000);
		valueTvTwo_x.setRepeatCount(0);
		valueTvTwo_x.setRepeatMode(ValueAnimator.REVERSE);
		valueTvTwo_x.setInterpolator(new DecelerateInterpolator());

		final ValueAnimator valueTvThree_x = ObjectAnimator.ofFloat(
				leftRightTvThree, "x", leftRightTvThree.getX(),
				screenWidth * .96f);// - 20);

		valueTvThree_x.setDuration(1000);
		valueTvThree_x.setRepeatCount(0);
		valueTvThree_x.setRepeatMode(ValueAnimator.REVERSE);
		valueTvThree_x.setInterpolator(new DecelerateInterpolator());

		animatorSet1 = new AnimatorSet();
		animatorSet1.playSequentially(valueTvOne_x, valueTvTwo_x,
				valueTvThree_x);

		animatorSet1.start();
		animatorSet1.addListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator animation) {
			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				ValueAnimator valueTvOne_x = ObjectAnimator.ofFloat(
						leftRightTvOne, "x", leftRightTvOne.getX(),
						leftRightTvOne.getX() * .01f);

				valueTvOne_x.setDuration(1000);
				valueTvOne_x.setRepeatCount(0);
				valueTvOne_x.setRepeatMode(ValueAnimator.REVERSE);
				valueTvOne_x.setInterpolator(new DecelerateInterpolator());

				final ValueAnimator valueTvTwo_x = ObjectAnimator.ofFloat(
						leftRightTvTwo, "x", leftRightTvTwo.getX(),
						leftRightTvTwo.getX() * .03f);

				valueTvTwo_x.setDuration(1000);
				valueTvTwo_x.setRepeatCount(0);
				valueTvTwo_x.setRepeatMode(ValueAnimator.REVERSE);
				valueTvTwo_x.setInterpolator(new DecelerateInterpolator());

				final ValueAnimator valueTvThree_x = ObjectAnimator.ofFloat(
						leftRightTvThree, "x", leftRightTvThree.getX(),
						leftRightTvThree.getX() * .06f);

				valueTvThree_x.setDuration(1000);
				valueTvThree_x.setRepeatCount(0);
				valueTvThree_x.setRepeatMode(ValueAnimator.REVERSE);
				valueTvThree_x.setInterpolator(new DecelerateInterpolator());

				animatorSet = new AnimatorSet();
				animatorSet.playSequentially(valueTvThree_x, valueTvTwo_x,
						valueTvOne_x);

				animatorSet.start();
				animatorSet.addListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator animation) {

					}

					@Override
					public void onAnimationRepeat(Animator animation) {

					}

					@Override
					public void onAnimationEnd(Animator animation) {
						animatorSet1.start();
					}

					@Override
					public void onAnimationCancel(Animator animation) {

					}
				});
			}

			@Override
			public void onAnimationCancel(Animator animation) {
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_HOME) {
			Log.i("Home Button", "Clicked");
		}
		return false;
	}

	@Override
	public void onBackPressed() {
		return;
	}

}
